#include "viewport.h"

#include "ioManager.h"

Viewport& Viewport::getInstance()
{
	static Viewport viewport;
	return viewport;
}

Viewport::Viewport() : 
	frozen(false),       
	gdata(Gamedata::getInstance()),
	position(0, 0),
	viewWidth(gdata.getXmlInt("viewWidth")), 
	viewHeight(gdata.getXmlInt("viewHeight")),
	worldWidth(gdata.getXmlInt("worldWidth")),
	worldHeight(gdata.getXmlInt("worldHeight")),
	objWidth(0), objHeight(0), objX(0),
	objectToTrack(NULL),
	crosshairFrame(SpriteFrameFactory::getInstance()->getFrame("crosshair"))
{
	
}

void Viewport::draw() const
{
	int x_coord, y_coord;
	SDL_GetMouseState(&x_coord, &y_coord);
	crosshairFrame->draw(0,0,x_coord-crosshairFrame->getWidth()/2, y_coord-crosshairFrame->getHeight()/2);
}

void Viewport::setObjectToTrack(const Sprite *obj)
{
	objectToTrack = obj; 
	objWidth = objectToTrack->getFrame()->getWidth();
	objHeight = objectToTrack->getFrame()->getHeight();
}

void Viewport::update()
{
	if ( frozen ) return;
	const float x = objectToTrack->X();
	objX =  static_cast<int>(x);
	const float y = objectToTrack->Y();
	position[0] = (x + objWidth/2) - viewWidth/2;
	position[1] = (y + objHeight/2) - viewHeight/2;
	if (position[0] < 0) position[0] = 0;
	if (position[1] < 0) position[1] = 0;
	if (position[0] > (worldWidth - viewWidth)) {
		position[0] = worldWidth-viewWidth;
	}
	if (position[1] > (worldHeight - viewHeight)) {
		position[1] = worldHeight-viewHeight;
	}
}
